<template>
  <h2>可操作的树</h2>
  <e-treeV2
    :data="dataSource"
    :props="defaultProps"
    node-key="id"
    :default-expanded-keys="[4]"
    @node-click="handleNodeClick"
    :expand-on-click-node="false">
    <template #default="{ node, data }">
      <div class="custom-tree-node">
        <span v-if="!node['isSelfEdit']">{{ data.label }}</span>
        <template v-if="node['isSelfEdit']">
          <e-input v-model="data.label" size="small" />
        </template>

        <span class="my-operations">
          <e-icon type="edit-1" @click="toEdit(node, data)" v-show="!node['isSelfEdit']"></e-icon>
          <e-icon type="check" @click="toSave(node, data)" v-if="node['isSelfEdit']"></e-icon>
          <e-icon type="close" @click="toRemove(node, data)"></e-icon>
          <e-icon type="more" style="rotate: 90deg;"></e-icon>
        </span>
      </div>
    </template>
  </e-treeV2>
</template>

<script setup>
import { ref } from "vue"
const dataSource = ref([
  {
    id: 1,
    label: 'Level one 1',
    children: [
      {
        id: 4,
        label: 'Level two 1-1',
        children: [
          {
            id: 9,
            label: 'Level three 1-1-1',
          },
          {
            id: 10,
            label: 'Level three 1-1-2',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: 'Level one 2',
    children: [
      {
        id: 5,
        label: 'Level two 2-1',
      },
      {
        id: 6,
        label: 'Level two 2-2',
      },
    ],
  },
  {
    id: 3,
    label: 'Level one 3',
    children: [
      {
        id: 7,
        label: 'Level two 3-1',
      },
      {
        id: 8,
        label: 'Level two 3-2',
      },
    ],
  },
])

const defaultProps = {
  children: 'children',
  label: 'label',
}

const handleNodeClick = (data) => {
  console.log(data)
}

const toEdit = (node, data) => {
  node['isSelfEdit'] = true
}

const toSave = (node, data) => {
  node['isSelfEdit'] = false
}

const toRemove = (node, data) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children?.findIndex((d) => d.id === data.id)
  children.splice(index, 1)
  dataSource.value = [...dataSource.value]
}
</script>

<style scoped>
h2 {
  margin: 26px 0px;
}

.haloe-icon {
  margin-left: 8px;

  &:hover {
    color: #2D8cF0;
  }
}

.my-operations {
  display: none;
}

:deep(.custom-tree-node) {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  height: 26px;
  padding-right: 8px;
}

:deep(.haloe-tree-node__content:hover>.custom-tree-node>.my-operations) {
  display: flex;
  align-items: center;
}

:deep(.haloe-tree-node:focus>.haloe-tree-node__content>.custom-tree-node>.my-operations) {
  display: flex;
  align-items: center;
}
</style>